package com.geqian.web.generator;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author geqian
 * @date 17:00 2023/11/20
 */
@Component
@EnableConfigurationProperties({OutputFileProperties.class, TemplateFileProperties.class})
public class FileMappingHandler {

    @Resource
    private OutputFileProperties outputFileProperties;

    @Resource
    private TemplateFileProperties templateFileProperties;


    private Map<String, String> fileRelationshipMapping;


    @PostConstruct
    private void handlerFileMapping() throws IllegalAccessException {
        fileRelationshipMapping = new HashMap<>();
        Field[] outputFields = outputFileProperties.getClass().getDeclaredFields();
        Field[] templateFields = templateFileProperties.getClass().getDeclaredFields();
        for (Field outputField : outputFields) {
            for (Field templateField : templateFields) {
                if (outputField.getName().equals(templateField.getName())) {
                    outputField.setAccessible(true);
                    templateField.setAccessible(true);
                    String outputFile = (String) outputField.get(outputFileProperties);
                    File file = new File(outputFile.substring(0, outputFile.lastIndexOf("\\") + 1));
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    String templateFile = (String) templateField.get(templateFileProperties);
                    fileRelationshipMapping.put(templateFile, outputFile);
                }
            }
        }
    }

    public Map<String, String> getFileRelationshipMapping(String className) {
        return fileRelationshipMapping.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
                entry -> entry.getValue().replace("#{className}", className),
                (oldValue, newVlaue) -> oldValue));
    }


    public String getEntityPath() {
        String entityFile = outputFileProperties.getEntity();
        return entityFile.substring(0, entityFile.lastIndexOf(File.separator));
    }
}
